package com.rockcent.mall.lib.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by oyhk on 16/7/29.
 *
 *
 * 中间表 需要自己实现,暂时不想使用hibernate 映射关联插入
 */
@Component
public class ChannelCategoryRepository {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    public void save(Long channelId, Long categoryId) {
        Map<String, Object> params = new HashMap<>();
        params.put("channelId", channelId);
        params.put("categoryId", categoryId);
        int i=jdbcTemplate.update("insert into channel_category values(:channelId,:categoryId)", params);
    }

    public void delete(Long channelId) {
        Map<String, Object> params = new HashMap<>();

        params.put("channelId", channelId);
        jdbcTemplate.update("delete from channel_category where channel_product_types_id=:channelId",params);
        //int i=jdbcTemplate.update("update channel_category set category_id=:categoryId WHERE channel_product_types_id=:channelId", params);

    }

    public List<Map> getCategoryByChannelId(Long channelId) {
        Map<String, Object> params = new HashMap<>();

        params.put("channelId", channelId);
       return jdbcTemplate.query("SELECT c.name,cc.category_id FROM channel_category cc LEFT JOIN category c ON c.id=cc.category_id WHERE channel_product_types_id=:channelId", params, new RowMapper<Map>() {

           @Override
           public Map mapRow(ResultSet resultSet, int i) throws SQLException {
               Map row=new HashMap();
               row.put("categoryId", resultSet.getLong("category_id"));

               return row;
           }
       });
    }
}
